/**
 * 
 */
package dk.dtu.is.utility.settings;

import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import dk.dtu.is.model.settings.AppSettings;

/**
 * @author dsac
 *
 */
public final class AppSettingsHelper {
	
	public static final String settingsFileName = "PowerlabClientSettings.xml";
	
	public AppSettings appSettings;
	
	
	/**
	 * Private Constructor
	 * This class won't be instantiated 
	 */
	public AppSettingsHelper() {
		File settingsFile;
		try {
			settingsFile = this.readSettingsFile();
			parseSettingsFile(settingsFile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * It loads that settings from an XML file.
	 * The XML file must have the following structure (for example)
	 * 
	 * {@code
	 * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
	 * <IEC61850ServerSettings>
	 * 	<IpAddress>http://10.59.16.211</IpAddress>
	 * 	<PortNumber>8081</PortNumber>
	 * 	<LogicalNode>T2GCHR/ZCEV1</LogicalNode>
	 * </IEC61850ServerSettings>
	 * }
	 * 
	 * @param iec61850ServerSettingsFile this is the xml file which ocntains the settings informations
	 * @return true if the informations have been successfully parsed
	 */
	private void parseSettingsFile (File settingsFile) throws JAXBException { 
	
		// load the data using JAXB
		JAXBContext jc = null;
		Unmarshaller unmarshaller = null;
		
		jc = JAXBContext.newInstance(AppSettings.class);
		unmarshaller = jc.createUnmarshaller();
		appSettings = (AppSettings) unmarshaller.unmarshal( settingsFile );
	}
	
	/**
	 * It loads the settings file for this client
	 * 
	 * The file should be in XML format and should be within the current working directory
	 * The name of the file should be @link{settingsFileName settingsFileName}
	 * 
	 * @return the settings file if it exists
	 */
	private File readSettingsFile() throws IOException {
		
		// this is the full path of the settings file.
		// it should be in the working directory
		String settingsFilePath = System.getProperty("user.dir") + 
				System.getProperty("file.separator") + 
				settingsFileName;
		
		// read the file
		File settingsFile = new File(settingsFilePath);
		
		// throw an exception if it does not exist
		if ( !(settingsFile.exists()))
			throw (new IOException(
					"Client settings file not found. " +
					"A file called " + settingsFileName + " should be within the folder" +
					System.getProperty("user.dir")
				)
			); 
		
		return settingsFile;
	}
}
